package com.radiosamhan.ryoko;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

public class TelnetClient {
	private Socket _socket = null;
	private BufferedReader _bufferedReader = null;
	private BufferedWriter _bufferedWriter = null;
	private Boolean _isConnected = false;

	public TelnetClient() {
	}

	public Boolean connect(String host, int port) throws IOException {
		try {
			InetSocketAddress address = new InetSocketAddress(host, port);
			_socket = new Socket();
			_socket.connect(address, 100);
			_bufferedWriter = new BufferedWriter(new OutputStreamWriter(
					_socket.getOutputStream()));
			_bufferedReader = new BufferedReader(new InputStreamReader(
					_socket.getInputStream()));
			//_bufferedReader.readLine(); // Clear buffer
			//_socket.setKeepAlive(true);
			_isConnected = true;
			return true;
		} catch (IOException e) {
			throw e;
		}
	}

	public void disconnect() {
		try {
			_isConnected = false;
			_socket.close();
		} catch (IOException e) {
		}
	}

	public boolean isConnected() {
		return _isConnected && _socket.isConnected();
	}

	public String attention(String command) {
		if (!isConnected())
			return "Not connected";

		String result = "";
		try {
			_bufferedWriter.write(command + "\n", 0, command.length() + 1);
			_bufferedWriter.flush();
		} catch (IOException e) {
			_isConnected = false;
			result = "Write failed";
		}
		if (_isConnected) {
			try {
				result = _bufferedReader.readLine();
			} catch (IOException e) {
				result = "Read failed";
			}
		}
		return result;
	}
	
}
